#include "myid.h"
#include "id3UI.h"

#include <QTextCodec>
#include <QLineEdit>
#include <QLabel>
#include <QPushButton>
#include <QGridLayout>
#include <QFileDialog>
#include <QDateTime>
#include <QDir>
#include <QTimer>

#include <QMessageBox>
#include <QDebug>

CMyId3UI::CMyId3UI( QWidget* parent )
		: QDialog( parent )
{
	InitGui();
	OtherInit();
	
	m_bComplete = false;
	m_pTimer = new QTimer( this );
    
	connect( m_pTimer, SIGNAL( timeout() ), this, SLOT( IsComplete() ));
	connect( m_openBtn,  SIGNAL( clicked() ), SLOT( OpenDirPath() ) );
	connect( m_startBtn, SIGNAL( clicked() ), SLOT( BeforeProcess() ) );
	connect( m_helpBtn, SIGNAL( clicked() ), SLOT( Help() ) );
}

void CMyId3UI::InitGui( void )
{
	m_DirPathLineEdit = new QLineEdit( QString::fromUtf8( "选择文件夹路径" ), this );
	m_helpBtn         = new QPushButton( QString::fromUtf8( "帮助" ), this );
	m_SuffixLineEdit  = new QLineEdit( "", this );
	m_inforLabel      = new QLabel( QString::fromUtf8( "任务未开始" ), this );
	m_openBtn         = new QPushButton( QString::fromUtf8( "打开" ), this );
	m_startBtn        = new QPushButton( QString::fromUtf8( "开始" ), this );

	QFont font( "Helvetica", 15 );

	m_DirPathLineEdit->setGeometry( 10, 10, 580, 40 );
	m_DirPathLineEdit->setFont( font );

	m_helpBtn->setGeometry( 600, 10, 90, 40 );
	m_helpBtn->setFont( font );

	m_SuffixLineEdit->setGeometry( 10, 60, 280, 40 );
	m_SuffixLineEdit->setFont( font );

	m_inforLabel->setGeometry( 300, 60, 190, 40 );
	m_inforLabel->setFont( font );
	m_inforLabel->setFrameStyle( QFrame::Box );

	m_openBtn->setGeometry( 500, 60, 90, 40 );
	m_openBtn->setFont( font );
	
	m_startBtn->setGeometry( 600, 60, 90, 40 );
	m_startBtn->setFont( font );

	resize( 700, 110 );
}

void CMyId3UI::OtherInit( void )
{
	setWindowTitle( QString::fromUtf8( " 歌曲 ID3 信息处理软件 " ) );

	m_musicSuffixList<<"mp3"<<"aac"<<"flac"<<"m4a"<<"ape"<<"mp4";
	QString strTmp = m_musicSuffixList.join( ", " );
	m_SuffixLineEdit->setText( strTmp );
	
	//m_DirPathLineEdit->setText( "E:/Music/mp32/untitled folder/q" );  //testcode
}

void CMyId3UI::OpenDirPath( void )
{
	QString strDirPath  = QFileDialog::getExistingDirectory( this, 
				QString::fromUtf8( "打开文件夹" ), QDir::homePath(), /*QDir::currentPath(),*/
				QFileDialog::ShowDirsOnly | QFileDialog::DontResolveSymlinks );
	if( !strDirPath.isEmpty() )
	    m_DirPathLineEdit->setText( strDirPath );
}

void CMyId3UI::BeforeProcess( void )
{
	m_strSelectPath = m_DirPathLineEdit->text().trimmed();
	QDir curDir( m_strSelectPath );
	if( m_strSelectPath.isEmpty() || !curDir.exists() )
	{
	    m_DirPathLineEdit->setText( QString::fromUtf8( " 路径不存在!!! " ) );
		return;
	}
	
	m_bComplete = false;
	m_startBtn->setEnabled( false );
	m_openBtn->setEnabled( false );
	m_helpBtn->setEnabled( false );
	m_inforLabel->setText( QString::fromUtf8( "处理中, 请等待..." ) );
	
	QTimer::singleShot( 50, this, SLOT( Process() ) );
}

void CMyId3UI::Process( void )
{
	//add a repeat timer check if complete
    m_pTimer->start( 1000 );

	//mkdir target
	QString strTarget = QDir::currentPath() + QDir::separator() + "targetDirs";
	QDir dirTarget( strTarget );
	if( !dirTarget.exists() )
	    dirTarget.mkdir( strTarget );

	//mkdir according to datetime string
	QDateTime dateTime = QDateTime::currentDateTime();
	m_strDateTimeDir = strTarget + QDir::separator() + dateTime.toString( "yyyy_MM_dd_hh_mm_ss" );
	QDir dir;
	if( !m_strDateTimeDir.isEmpty() )
	    dir.mkdir( m_strDateTimeDir );

	//add extra music suffix
	QString strGetSuffix = m_SuffixLineEdit->text().trimmed().replace( " ", "" ).toLower();
	QStringList strListMusicSuffix = strGetSuffix.split( ",", QString::SkipEmptyParts );
	QString strAdd;

	m_musicSuffixList.clear();
	foreach( strAdd, strListMusicSuffix )
	{
		if( -1 == m_musicSuffixList.indexOf( strAdd ) )
			m_musicSuffixList<<strAdd;
	}

	//testcode
	//qDebug()<<m_strDateTimeDir;
	//qDebug()<<m_musicSuffixList;
	GetMusicPathList( m_strSelectPath );
	
	m_bComplete = true;
}

void CMyId3UI::GetMusicPathList( const QString& strCurPath )
{
	QDir curDir( strCurPath );
	
	//Get music lists
	QFileInfoList musicInfoList = curDir.entryInfoList( QDir::NoDotAndDotDot |
				QDir::AllEntries | QDir::NoSymLinks );

	for( int i=0; i<musicInfoList.size(); ++i )
	{
		QFileInfo info = musicInfoList[i];
		if( FilterSuffix( info.suffix() ) )
		    ProcessMusics( info.absoluteFilePath() );
		else if( info.isDir() )
			GetMusicPathList( info.absoluteFilePath() );
	}
}

bool CMyId3UI::FilterSuffix( const QString& strMusic )
{
	//change to lower
	QString strMusicTmp = strMusic.toLower();

	if( -1 == m_musicSuffixList.indexOf( strMusicTmp ) )
	    return false;
	else
	    return true;
}

void CMyId3UI::GetID3Artist( QString& strArtist, const QString& strMusicPath )
{
	QTextCodec *codec = QTextCodec::codecForName( "GB18030" ); // get the codec for KOI8-R
	QString strName = codec->fromUnicode( strMusicPath );

	CMyID Id3;
	char pszArtist[128] = "";

	Id3.Album( pszArtist, (const char*)strName.toStdString().c_str() );

	strArtist = QString::fromUtf8( pszArtist );
}

void CMyId3UI::Move( const QString& strTo, const QString& strFrom )
{
	//qDebug()<<"----------------------------------------------------------star";
	
	QFileInfo infoMusic( strFrom );
	QString strFinalAddress = strTo + QDir::separator() + infoMusic.fileName();
	
	if( QFile::exists( strFinalAddress ) )
	    strFinalAddress = strTo + QDir::separator() + "1_" + infoMusic.fileName();
	
	//qDebug()<< "from: " << strFrom;
	//qDebug()<< "to: " << strFinalAddress;
	
	//todo
	if( !QFile::copy( strFrom, strFinalAddress ) )
	{
		//msg.showMessage( QString::fromUtf8( "复制文件出错!!!" ) );
		qDebug()<<"复制文件出错!!!";
	}
	
	//qDebug()<<"----------------------------------------------------------end";
}

void CMyId3UI::ProcessMusics( const QString& strMusicPath )
{
	QString strArtist;
	GetID3Artist( strArtist, strMusicPath );
	if( strArtist.isEmpty() )
	    strArtist = "others";

	QString strArtistDirPath = m_strDateTimeDir + QDir::separator() + strArtist;

	//if copy dir not exist, mkdir 
	QDir dirPath = QDir( strArtistDirPath );
	if( !dirPath.exists() )
		dirPath.mkdir( strArtistDirPath );
	
	//move to target dir;
	Move( strArtistDirPath, strMusicPath );
}

void CMyId3UI::IsComplete( void )
{
	if( m_bComplete )
	{
		//qDebug()<<"yyyyyyyyyyyyyyyyyy";
		m_inforLabel->setText( QString::fromUtf8( "处理完成..." ) );
		m_startBtn->setEnabled( true );
		m_openBtn->setEnabled( true );
		m_helpBtn->setEnabled( true );
		m_pTimer->stop();
		m_inforLabel->setFocus();
	}
}

void CMyId3UI::Help( void )
{
	QString strHelp = QString::fromUtf8(
				"<font size = 5>"
	            "使用说明:<br>"
	            "读取歌曲的ID3信息,根据ID3中的Album将歌曲分类<br><br>"
	            "使用方法:<br>"
				"1: 选择要处理的音乐文件夹路径<br>"
				"2: 选择要处理的音乐文件类型(逗号隔开),如mp3,ogg<br>"
				"3: 按<开始>按钮开始处理音乐文件<br>"
				"</font size>" );
	QMessageBox::about( this, QString::fromUtf8( "关于软件" ), strHelp );
}

